//
//  MineViewController.m
//  Feel_at_home
//
//  Created by dlios on 15/9/23.
//  Copyright © 2015年 Feel_at_home. All rights reserved.
//

#import "MineViewController.h"
#import "Constants.h"
#import "WidthAndHeight.pch"
#import "CollectView.h"
#import "AboutViewController.h"

@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UIImageView *imageBack;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSMutableArray *arr;
@property (nonatomic, copy) NSString *string;
@property (nonatomic, copy) NSString *nit;

@end

@implementation MineViewController

- (void)viewWillAppear:(BOOL)animated
{
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = kMine;
    [self tableViewSubViews];
}

// tableView
- (void)tableViewSubViews
{
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *strpath = [cachesPath stringByAppendingPathComponent:@"location.txt"];
    
    NSError *error = nil;
    self.nit = [NSString stringWithContentsOfFile:strpath encoding:NSUTF8StringEncoding error:&error];
    if (self.nit == nil) {
        self.nit = @"1";
    }
    
    self.arr = @[@"收藏", @"清除缓存", @"夜间模式", @"关于我们", @"版本信息", @"意见反馈"].mutableCopy;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VCWIDTH, VCHEIGH - 20 * HEIGH) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.contentInset = UIEdgeInsetsMake(240 * HEIGH, 0, 0, 0);
    self.imageBack = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xinqing"]];
    self.imageBack.frame = CGRectMake(0, -240 * HEIGH, VCWIDTH, 240 * HEIGH);
    
    [self.tableView addSubview:self.imageBack];
}

// tableView协议方法
// 
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y  = scrollView.contentOffset.y;
    CGFloat x = (y + 240 * HEIGH) / 2;
    if (y < -240 * HEIGH) {
        self.imageBack.frame = CGRectMake(x, y, VCWIDTH + fabsf(x) * 2, -y);
    }
}
// 每行cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
// row
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
// cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *myCell = @"MyCellIndifer";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myCell];
    cell.textLabel.font = [UIFont systemFontOfSize:20];
//    cell.imageView.frame = CGRectMake(10, 10, 30, 30);
    if (indexPath.row == 1) {
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        CGFloat size = [self folderSizeAtPath:caches];
        cell.textLabel.text = [NSMutableString stringWithFormat:@"%@ 缓存:%.2fM", [self.arr objectAtIndex:indexPath.row], size];
        cell.imageView.image = [UIImage imageNamed:@"shanchu"];
    } else if (indexPath.row == 0) {
        
        cell.textLabel.text = self.arr[indexPath.row];
        cell.imageView.image = [UIImage imageNamed:@"shoucang"];
    } else if (indexPath.row == 2) {
        if ([self.nit isEqualToString:@"1"]) {
            
            cell.textLabel.text = self.arr[indexPath.row];
            cell.imageView.image = [UIImage imageNamed:@"yejianzhuanhuan"];
        } else {
            
            cell.textLabel.text = @"白天模式";
            cell.imageView.image = [UIImage imageNamed:@"rijianmoshi"];
        }
        
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *strpath = [cachesPath stringByAppendingPathComponent:@"location.txt"];
        
        NSError *error = nil;
        [self.nit writeToFile:strpath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    } else {
        cell.textLabel.text = self.arr[indexPath.row];
        if (indexPath.row == 3) {
            cell.imageView.image = [UIImage imageNamed:@"guanyuwomen"];
        } else if (indexPath.row == 4){
            cell.imageView.image = [UIImage imageNamed:@"banbenxinxi"];
        } else {
            cell.imageView.image = [UIImage imageNamed:@"yijianfankui"];
        }
    }
    cell.accessoryType = 1;
    return cell;
}

// cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 1) {
        UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"警告" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            [self clearCache:caches];
            
        }];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            
        }];
        [aler addAction:action];
        [aler addAction:action1];
        [self presentViewController:aler animated:YES completion:^{
            
            
        }];
    } else if (indexPath.row == 0) {
        CollectView *collect = [[CollectView alloc] init];
        [self.navigationController pushViewController:collect animated:YES];
        
    } else if (indexPath.row == 2) {
        if ([self.nit isEqualToString:@"1"]) {
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"change" object:[UIColor blackColor] userInfo:nil];
            self.nit = @"2";
            [self.tableView reloadData];
        } else {
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"change" object:[UIColor clearColor] userInfo:nil];
            self.nit = @"1";
            [self.tableView reloadData];
        }
    } else if (indexPath.row == 3) {
        AboutViewController *we = [[AboutViewController alloc] init];
        we.str1 = @"关于我们";
        we.str2 = @"心情家居APP希望为所有人提供最有价值、最需要的信息。我们相信，我们可以在互联网上借助技术的力量做到这一点。我们相信，我们可以借助技术的力量，为所有人提供最有价值、最需要的信息";
        
        
        [self.navigationController pushViewController:we animated:YES];
    } else if (indexPath.row == 4) {
        AboutViewController *we = [[AboutViewController alloc] init];
        we.str1 = @"版本信息";
        we.str2 = @"      心情家居APP2.0\n      2.0版本除了修复了1.0版本的bug之外, 还添加了一个新选择, 里边有一个电台跟一个小笑话, 可以舒缓你的心情.o(^_^)o";
        
        
        [self.navigationController pushViewController:we animated:YES];
    } else if (indexPath.row == 5) {
        AboutViewController *we = [[AboutViewController alloc] init];
        we.str1 = @"意见反馈";
        we.str2 = @"如果你对我们的软件有什么不满或者有更好的建议可以反馈给我们, 我们会接纳你的意见并参考你的意见开发更好的APP, 我们的反馈邮箱为:15104578312@163.com";
        
        
        [self.navigationController pushViewController:we animated:YES];
    }
}

//通常用于删除缓存的时，计算缓存大小
//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float)folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
/* 清除缓存 */
- (void)clearCache:(NSString *)path
{
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {
        
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        
        for (NSString *fileName in childerFiles) {
            
            //如有需要，加入条件，过滤掉不想删除的文件
            
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
        
    }
    [self.tableView reloadData];
    
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
